#include "configuredialog.h"
#include <QWidget>
#include <QFileDialog>
#include <QMessageBox>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <dirent.h>
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <cstdlib>
#include <ctime>
#include <typeinfo>
#include <string.h>
#include <curl/curl.h>
#include <unistd.h>
#include <string.h>
#include<iomanip>

#define MAXCLOCKRATE 500000000
using namespace std;

ConfigureDialog::ConfigureDialog(QDialog *parent)
    : QDialog(parent)
{
    ui.setupUi(this);
        //Set the minimum and close button of the main frame.
        this->setWindowFlags(Qt::WindowFlags(Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint));

        connect(ui.cmbDevice, SIGNAL(currentIndexChanged(int)), this, SLOT(DeviceChanged(int)));
        connect(ui.btnOK, SIGNAL(clicked()), this, SLOT(ButtonOKClicked()));
        connect(ui.btnCancel, SIGNAL(clicked()), this, SLOT(ButtonCancelClicked()));
        connect(ui.btnBrowse, SIGNAL(clicked()), this, SLOT(ButtonBrowseClicked()));

        //Set the maximum value of clock rate per channel 500MHz = 500000000.
        connect(ui.login,SIGNAL(clicked),this,SLOT(on_login_clicked()));
        ui.edtClockRatePerChan->setValidator(new QDoubleValidator(1, MAXCLOCKRATE, 2, this));

        ui.groupBox->setEnabled(0);

        Initailization();

    }
    void ConfigureDialog::on_login_clicked()
    {

        if(ui.Username->text() == tr("admin") && ui.Password->text() == tr("123"))
            {
                    // 清空输入框内容
               ui.Username->clear();
               ui.Password->clear();  ui.groupBox->setEnabled(1);
               ui.Username->clear();
               ui.Password->clear();
             }
             else
             {                              //标题              内容                OK按钮
                QMessageBox::warning(this, tr("警告！"),tr("用户名或密码错误！"),QMessageBox::Yes);


            }

    }

ConfigureDialog::~ConfigureDialog()
{

}

void ConfigureDialog::Initailization()
{
    WaveformAiCtrl * waveformAiCtrl = WaveformAiCtrl::Create();
    Array<DeviceTreeNode> *supportedDevice = waveformAiCtrl->getSupportedDevices();

    if (supportedDevice->getCount() == 0)
    {
        QMessageBox::information(this, tr("Warning Information"),
            tr("No device to support the currently demonstrated function!"));
        QCoreApplication::quit();
    }
    else
    {
        ui.cmbDevice->blockSignals(true);
        for (int i = 0; i < supportedDevice->getCount(); i++)
        {
            DeviceTreeNode const &node = supportedDevice->getItem(i);
            qDebug("%d, %ls\n", node.DeviceNumber, node.Description);
            QString description = QString::fromWCharArray(node.Description);
            ui.cmbDevice->addItem(description);
        }
         ui.cmbDevice->blockSignals(false);
         ui.cmbDevice->setCurrentIndex(0);
         DeviceChanged(0);
    }
    waveformAiCtrl->Dispose();
    supportedDevice->Dispose();
}

void ConfigureDialog::CheckError(ErrorCode errorCode)
{
    if (errorCode >= 0xE0000000 && errorCode != Success)
    {
        QString message = tr("Sorry, there are some errors occurred, Error Code: 0x") +
            QString::number(errorCode, 16).right(8).toUpper();
        QMessageBox::information(this, "Warning Information", message);
    }
}

void ConfigureDialog::DeviceChanged(int index)
{
    ui.cmbChannelCount->clear();
    ui.cmbChannelStart->clear();
    ui.cmbValueRange->clear();

    std::wstring description = ui.cmbDevice->currentText().toStdWString();
    DeviceInformation selected(description.c_str());

    WaveformAiCtrl * waveformAiCtrl = WaveformAiCtrl::Create();
    ErrorCode errorCode = waveformAiCtrl->setSelectedDevice(selected);
    ui.btnOK->setEnabled(true);
    if (errorCode != 0){
        QString str;
        QString des = QString::fromStdWString(description);
        str.sprintf("Error:the error code is 0x%x\n\
                   The %s is busy or not exit in computer now.\n\
                   Select other device please!", errorCode, des.toUtf8().data());
        QMessageBox::information(this, "Warning Information", str);
        ui.btnOK->setEnabled(false);
        return;
    }

   int channelCount = (waveformAiCtrl->getChannelCount() < 16) ?
      waveformAiCtrl->getChannelCount() : 16;
    int logicChannelCount = waveformAiCtrl->getChannelCount();

    for (int i = 0; i < channelCount; i++)
    {
        ui.cmbChannelCount->addItem(QString("%1").arg(i + 1));
    }

    for (int i = 0; i < logicChannelCount; i++)
    {
        ui.cmbChannelStart->addItem(QString("%1").arg(i));
    }


    Array<ValueRange> * ValueRanges = waveformAiCtrl->getFeatures()->getValueRanges();
    wchar_t			vrgDescription[128];
    MathInterval	ranges;
    ValueUnit		valueUnit;
    for(int i = 0; i < ValueRanges->getCount(); i++)
    {
        errorCode = AdxGetValueRangeInformation(ValueRanges->getItem(i),
            sizeof(vrgDescription), vrgDescription, &ranges, &valueUnit);
        CheckError(errorCode);

        //we filter the Celsius degree for the buffered AI can not support this function.
        if (valueUnit == CelsiusUnit)
        {
            continue;
        }

        QString str = QString::fromWCharArray(vrgDescription);
        ui.cmbValueRange->addItem(str);

        ifstream in;
        in.open("param.txt");
        char data[1024];
        in.getline(data, 1024);
        ui.edtClockRatePerChan->setText(data);
        memset(data,0,1024);
        in.getline(data, 1024);
        ui.edtSectionLength->setText(data);
        memset(data,0,1024);
        in.getline(data, 1024);
        ui.ip_adress->setText(data);
        memset(data,0,1024);

        in.getline(data, 1024);
       // string a=data;
      //  int s = std::stoi(a);
        ui.cmbChannelCount->setCurrentText(data);
        memset(data,0,1024);
        in.getline(data, 1024);
        //string b=data;
        //int w = std::stoi(a);
        ui.cmbChannelStart->setCurrentText(data);
        memset(data,0,1024);
        in.getline(data, 1024);
        string e=data;
        int z = std::stoi(e);
        ui.cmbValueRange->setCurrentIndex(z);

    }
    waveformAiCtrl->Dispose();


    //Set the default value.

    /*ui.cmbChannelStart->setCurrentIndex(0);
    ui.cmbChannelCount->setCurrentIndex(0);
    ui.cmbValueRange->setCurrentIndex(0);*/
}
void ConfigureDialog::xml(QString Clock,QString Time,QString ip_adress,QString channelCount,QString channelStart,QString valueRange)
{
    ofstream outfile("param.txt");
    string a = Clock.toStdString();
    string b = Time.toStdString();
    string c = ip_adress.toStdString();
    string d = channelCount.toStdString();
    string e = channelStart.toStdString();
    string f = valueRange.toStdString();
    outfile<<a<<endl;
    outfile<<b<<endl;
    outfile<<c<<endl;
    outfile<<d<<endl;
    outfile<<e<<endl;
    outfile<<f<<endl;
    outfile.close();
}
void ConfigureDialog::ButtonOKClicked()
{
    if (ui.cmbDevice->count() == 0)
    {
        QCoreApplication::quit();
    }

    double clockRate = ui.edtClockRatePerChan->text().toDouble();
    if (clockRate < 1 || clockRate > MAXCLOCKRATE)
    {
        QMessageBox::information(this, tr("Warning Information"),
            tr("Sorry, the clock rate per channel is invalid"));
        return;
    }

    std::wstring description = ui.cmbDevice->currentText().toStdWString();
    DeviceInformation selected(description.c_str());

    WaveformAiCtrl * waveformAiCtrl = WaveformAiCtrl::Create();
    ErrorCode errorCode = waveformAiCtrl->setSelectedDevice(selected);
    CheckError(errorCode);

    Array<ValueRange> * ValueRanges = waveformAiCtrl->getFeatures()->getValueRanges();
    configure.deviceName = ui.cmbDevice->currentText();
    configure.channelCount = ui.cmbChannelCount->currentText().toInt();
    configure.channelStart = ui.cmbChannelStart->currentText().toInt();
    configure.valueRange = ValueRanges->getItem(ui.cmbValueRange->currentIndex());
    configure.clockRatePerChan = ui.edtClockRatePerChan->text().toDouble();

    int b=ui.edtClockRatePerChan->text().toDouble();
    int a=ui.edtSectionLength->text().toInt();
    configure.sectionLength = a*b;//将sectionLenth变量成ClockRatePerchan*采集秒数

    QString c=ui.edtClockRatePerChan->text();
    QString s=ui.edtSectionLength->text();
    QString i=ui.ip_adress->text();
    QString channelCount = QString("%1").arg(ui.cmbChannelCount->currentText());
    QString channelStart = QString("%1").arg(ui.cmbChannelStart->currentText());
    QString valueRange = QString("%1").arg(ui.cmbValueRange->currentIndex());


    xml( c, s, i,channelCount,channelStart,valueRange);
    waveformAiCtrl->Dispose();
    this->accept();
}
void ConfigureDialog::ButtonCancelClicked()
{
    this->reject();
}

void ConfigureDialog::ButtonBrowseClicked()
{
    QString str = QFileDialog::getOpenFileName(this, tr("Open Profile"), "../../profile", tr("Image Files(*.xml)"));
    ui.txtProfilePath->setText(str);
    configure.profilePath = str;
}

void ConfigureDialog::RefreshConfigureParameter()
{
    std::wstring description = ui.cmbDevice->currentText().toStdWString();
    DeviceInformation selected(description.c_str());

    WaveformAiCtrl * waveformAiCtrl = WaveformAiCtrl::Create();
    ErrorCode errorCode = waveformAiCtrl->setSelectedDevice(selected);
    CheckError(errorCode);

    ui.edtClockRatePerChan->setText(QString::number(waveformAiCtrl->getConversion()->getClockRate(), 'f',0));

    ui.groupBox->setEnabled(0);
    Initailization();


   // waveformAiCtrl->Dispose();

    //ui.edtSectionLength->setText(ui.edtSectionLength->text());
    if(ui.Username->text() == tr("admin") && ui.Password->text() == tr("123"))
        {
        }
        else
        {                              //标题              内容                OK按钮
         // QMessageBox::warning(this, tr("警告！"),tr("用户名或密码错误！"),QMessageBox::Yes);

        // 清空输入框内容
           ui.Username->clear();
           ui.Password->clear();
        }
}
